let DataList1=[];
let DataList2=[];
let DataList3=[];
let DataList4=[];
let checkType=false;
(function(){
     //表格初始化时间
     GetAnalysisWindowFiterTimes('chart1_time', 'd', false); 
     $('#chart1_time').daterangepicker(null, function (start, end, label) {
        times = $("#chart1_time").val();
        getWaterLevel(null,times);
    });

    GetAnalysisWindowFiterTimes('chart2_time', 'd', false); 
    $('#chart2_time').daterangepicker(null, function (start, end, label) {
       times = $("#chart2_time").val();
       getChart2(null,times);
   });

     GetAnalysisWindowFiterTimes('chart3_time', 'd', false); 
     $('#chart3_time').daterangepicker(null, function (start, end, label) {
        times = $("#chart3_time").val();
        getChart3(null,times);
    });
    GetAnalysisWindowFiterTimes('chart4_time', 'd', false); 
     $('#chart4_time').daterangepicker(null, function (start, end, label) {
        times = $("#chart4_time").val();
        getChart4(null,times);
    });

    GetAnalysisWindowFiterTimes('lastTime', 'd', false); 
    $('#lastTime').daterangepicker(null, function (start, end, label) {
       times = $("#lastTime").val();
       getTableData(null,times);
   });
 
    //获取站点
    $.get("http://192.168.9.59:18902/stationEquipment/findAllStations", function (res) {
        if (res.data && res.data.length>0) {
            let data=res.data;
            for(let a=0;a<data.length;a++){
                $("#siteList").append("<option value='"+data[a].stationCode+"'>"+data[a].stationName+"</option>");
            }
            //用站点查询传感器
            let siteVal = $("#siteList option:selected").val();
            getSensor(siteVal)
        } else {
            $("#siteList").html("<label>暂无站点!</label>");
        }
    });
    $(".cycle a").on("click",function(){
        $(this).addClass("active").siblings().removeClass("active");
    })
    //日期选择函数
    function GetAnalysisWindowFiterTimes(valuetoid, type, event) {
        var ntime = new Date();
        if (type == 'd') {
                var dstart = ntime.format("MM/dd/yyyy");
                var dend = ntime.format("MM/dd/yyyy");
                $(".timeControl #" + valuetoid).val(dstart + " - " + dend);
        } else if (type == 'w') {
                var wstart = new Date(ntime.getTime() + (24 * 60 * 60 * -6 * 1000)).format("MM/dd/yyyy");
                var wend = ntime.format("MM/dd/yyyy");
                $(".timeControl #" + valuetoid).val(wstart + ' - ' + wend);
        } else if (type == 'm') {
                var mstart = new Date(ntime.getTime() + (24 * 60 * 60 * -30 * 1000)).format("MM/dd/yyyy");
                var mend = ntime.format("MM/dd/yyyy");
                $(".timeControl #" + valuetoid).val(mstart + ' - ' + mend);
        }
        eval(event);
    }
})();
//站点选中改变
function siteChange(){
    //用站点查询传感器
    let siteVal = $("#siteList option:selected").val();
    getSensor(siteVal)
}
// 查询传感器
function getSensor(val){
    $("#Chart1Select").empty();
    $("#Chart2Select").empty();
    $("#Chart3Select").empty();
    $("#Chart4Select").empty();
    $("#tableSelect").empty();
    $.post("http://192.168.9.59:18902/stationEquipment/findByValues",{stationCode:val,equipmentType:214,jscj:"",}, function (res) {
            if (res.data && res.data.length>0) {
                let data=res.data;
                for(let a=0;a<data.length;a++){
                    $("#Chart1Select").append("<option value='"+data[a].jscj+"' equipmentType='"+data[a].equipmentType+"' stationCode='"+data[a].stationCode+"' stationName='"+data[a].stationName+"'>"+data[a].equipmentName+"</option>");
                    $("#Chart2Select").append("<option value='"+data[a].jscj+"' equipmentType='"+data[a].equipmentType+"' stationCode='"+data[a].stationCode+"' stationName='"+data[a].stationName+"'>"+data[a].equipmentName+"</option>");
                    $("#Chart3Select").append("<option value='"+data[a].jscj+"' equipmentType='"+data[a].equipmentType+"' stationCode='"+data[a].stationCode+"' stationName='"+data[a].stationName+"'>"+data[a].equipmentName+"</option>");
                    $("#Chart4Select").append("<option value='"+data[a].jscj+"' equipmentType='"+data[a].equipmentType+"' stationCode='"+data[a].stationCode+"' stationName='"+data[a].stationName+"'>"+data[a].equipmentName+"</option>");
                    $("#tableSelect").append("<option value='"+data[a].jscj+"' equipmentType='"+data[a].equipmentType+"' stationCode='"+data[a].stationCode+"' stationName='"+data[a].stationName+"'>"+data[a].equipmentName+"</option>");
                }
            } else {
                $("#Chart1Select").html("<label>暂无站点!</label>");
                $("#Chart2Select").html("<label>暂无站点!</label>");
                $("#Chart3Select").html("<label>暂无站点!</label>");
                $("#Chart4Select").html("<label>暂无站点!</label>");
                $("#tableSelect").html("<label>暂无站点!</label>");
            }
            getallData();
    });
}
//日期格式化
function dateFormat(fmt, date) {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
}

//初始化获取图表数据
function getallData(){
    getWaterLevel();
    getChart2();
    getChart3();
    getChart4();
    getTableData();
}
//图表1传感器改变
function chart1SensorSelectChange(){
    var SelectSensorVal = $('#Chart1Select  option:selected').val();
    getWaterLevel(SelectSensorVal)
}
//图表2传感器改变
function chart2SensorSelectChange(){
    var SelectSensorVal = $('#Chart2Select  option:selected').val();
    getChart2(SelectSensorVal)
}
//图表3传感器改变
function chart3SensorSelectChange(){
    var SelectSensorVal = $('#Chart3Select  option:selected').val();
    getChart3(SelectSensorVal)
}
//图表3传感器改变
function chart4SensorSelectChange(){
    var SelectSensorVal = $('#Chart4Select  option:selected').val();
    getChart4(SelectSensorVal)
}
//table 传感器改变
function tableSelectChange(){
    var tableSelectVal = $('#tableSelect  option:selected').val();
    getTableData(tableSelectVal)
}

//获取水位数据
function getWaterLevel(SelectSensorVal,time){
    let selectSense=SelectSensorVal;let times=time;
    if(selectSense == undefined){
        selectSense=$("#Chart1Select option:selected").val(); 
    }
    if(times == undefined){
        times=$("#chart1TimeControl #chart1_time").val();
    }
    var startTimeSplit = times.split('-')[0].replace(" ", "").split('/'),
    endTimeSplit = times.split('-')[1].replace(" ", "").split('/');
    var startTime = startTimeSplit[2] + "-" + startTimeSplit[0] + "-" + startTimeSplit[1]+" 00:00:00";
    var endTime = endTimeSplit[2] + "-" + endTimeSplit[0] + "-" + endTimeSplit[1]+" 23:00:00";
    
    let url ="http://192.168.9.59:801/apis/result/queryAlllist/?"+"startTime="+startTime+"&endTime="+endTime+"&uniqure_code="+selectSense;
    // let url ="http://192.168.9.59:801/apis/result/queryAlllist/?"+"startTime="+startTime+"&endTime="+endTime+"&uniqure_code=03081400016";
    $.get(url, function (res) {
        if(res.msg=="success"){
            let dataList=[];
            res.data.forEach((li)=>{
                let column = li.column;
                let data = li.data;
                if(data){
                    for(let a=0;a<data.length;a++){
                        let li={}
                        for(let b=0;b<column.length;b++){
                              let key =column[b];
                              li[column[b]]=data[a][b];
                        }
                        dataList.push(li)
                  }
                }
               
            })
            showChart1(dataList)
        }
    })
}
function showChart1(data){
    let Xdata=[];let Ydata=[];let Zdata=[]; let TimeData=[];
    data.forEach((item)=>{
        Xdata.push(item.JCSJ888A030*1);
        Ydata.push(item.JCSJ888A031*1);
        Zdata.push(item.JCSJ888A032*1);
        TimeData.push(item.time)
  })

  let option={
    chart: {
            type: 'line',
            style: {fontFamily: "'Unica One', sans-serif"},
            plotBorderColor: '#606063',
            zoomType: 'x',
            spacingRight: 20,
            height: 390
    },
    colors: ['#E5561F', '#7FBF7F', '#7F7FFF', '#FF6F10', '#8756D8', '#310F39', '#FF7F7F'],
    title: {text: ''},
    credits: {enabled: false},
    exporting: {enabled: false},
    subtitle: {text: ''},
    xAxis: {
        // type: 'datetime',
        categories: TimeData,
        tickInterval:100,
		labels: {
            enabled: true,
			formatter: function() {
				let arr = this.value.split(" ");
				if(arr[1]){
					return arr[1];
				}else{
					return this.value;
				}
				
            }
          }
    },
    yAxis: [{ // Primary yAxis
        title: {
            text: '摄氏度(℃)',
            style: {
                color: '#89A54E'
            }
        },
    }, { // Secondary yAxis
        title: {
            text: '深度(m)',
            style: {
                color: '#4572A7'
            }
        },
        opposite: true
    },{ // Secondary yAxis
        title: {
            text: '电导率（mS/cm）',
            style: {
                color: '#00A4FF'
            }
        },
        opposite: true
    }],
    tooltip: {
        formatter: function () {
            if(this.series.name == "摄氏度"){
                let row;
                data.forEach((li)=>{
                        if(li.time == this.x){
                            row = li;
                        }
                })
                return "设备编码:[<b>" + row.JCSJ888A050 + "</b>]<br>时间:[" + row.time + "]<br>摄氏度:[" + row.JCSJ888A030 + "]";
            }else if(this.series.name == "深度"){
                let row;
                data.forEach((li)=>{
                    if(li.time == this.x){
                            row = li;
                    }
                })
                return "设备编码:[<b>" + row.JCSJ888A050 + "</b>]<br>时间:[" + row.time + "]<br>深度:[" + row.JCSJ888A031 + "(m)]";
            }else{
                let row;
                data.forEach((li)=>{
                    if(li.time == this.x){
                            row = li;
                    }
                })
                return "设备编码:[<b>" + row.JCSJ888A050 + "</b>]<br>时间:[" + row.time + "]<br>电导率:[" + row.JCSJ888A032 + "(mS/cm)]";
            }
        }
    },
    plotOptions: {
            spline: {
                lineWidth: 1.5,
                states: {hover: {lineWidth: 2.5}},
                marker: {enabled: false}
            }
    },
    series: [
            {
                type: 'line',
                name: '摄氏度',
                data:Xdata,
                yAxis:0
            }, 
            {
                type: 'line',
                name: '深度',
                data:Ydata,
                yAxis:1
            },
            {
                type: 'line',
                name: '电导率',
                data:Zdata,
                yAxis:1
            },
        ]
    }
    $("#chart1").highcharts(option);
}
//获取图表2的数据
function getChart2(SelectSensorVal,time){
    let selectSense=SelectSensorVal;let times=time;
    if(selectSense == undefined){
        selectSense=$("#Chart2Select option:selected").val(); 
    }
    if(times == undefined){
        times=$("#chart2_time").val();
    }
    var startTimeSplit = times.split('-')[0].replace(" ", "").split('/'),
    endTimeSplit = times.split('-')[1].replace(" ", "").split('/');
    var startTime = startTimeSplit[2] + "-" + startTimeSplit[0] + "-" + startTimeSplit[1]+" 00:00:00";
    var endTime = endTimeSplit[2] + "-" + endTimeSplit[0] + "-" + endTimeSplit[1]+" 23:00:00";
    let url ="http://192.168.9.59:801/apis/result/queryAlllist/?"+"startTime="+startTime+"&endTime="+endTime+"&uniqure_code="+selectSense;
    // let url ="http://192.168.9.59:801/apis/result/queryAlllist/?"+"startTime="+startTime+"&endTime="+endTime+"&uniqure_code=03081400016";
    $.get(url, function (res) {
        if(res.msg=="success"){
            let dataList=[];
            res.data.forEach((li)=>{
                let column = li.column;
                let data = li.data;
                if(data){
                    for(let a=0;a<data.length;a++){
                        let li={}
                        for(let b=0;b<column.length;b++){
                            let key =column[b];
                            li[column[b]]=data[a][b];
                        }
                        dataList.push(li)
                }
                }
            
            })
            showChart2(dataList);
        }
    })
}
function showChart2(data){
    let Xdata=[];let TimeData=[];
    data.forEach((item)=>{
        Xdata.push(item.JCSJ888A030*1);
        TimeData.push(item.time)
  })
  let option={
    chart: {
            type: 'line',
            style: {fontFamily: "'Unica One', sans-serif"},
            plotBorderColor: '#606063',
            zoomType: 'x',
            spacingRight: 20,
            height: 390
    },
    colors: ['#E5561F', '#7FBF7F', '#7F7FFF', '#FF6F10', '#8756D8', '#310F39', '#FF7F7F'],
    title: {text: ''},
    credits: {enabled: false},
    exporting: {enabled: false},
    subtitle: {text: ''},
    xAxis: {
        // type: 'datetime',
        categories: TimeData,
        tickInterval:30,
		labels: {
            enabled: true,
			formatter: function() {
				let arr = this.value.split(" ");
				if(arr[1]){
					return arr[1];
				}else{
					return this.value;
				}
				
            }
          }
    },
    yAxis: [{ // Primary yAxis
        title: {
            text: '摄氏度(℃)',
            style: {
                color: '#89A54E'
            }
        },
    }],
    tooltip: {
        formatter: function () {
            if(this.series.name == "摄氏度"){
                let row;
                data.forEach((li)=>{
                        if(li.time == this.x){
                            row = li;
                        }
                })
                return "设备编码:[<b>" + row.JCSJ888A050 + "</b>]<br>时间:[" + row.time + "]<br>摄氏度:[" + row.JCSJ888A030 + "]";
            }
        }
    },
    plotOptions: {
            spline: {
                lineWidth: 1.5,
                states: {hover: {lineWidth: 2.5}},
                marker: {enabled: false}
            }
    },
    series: [{
                type: 'line',
                name: '摄氏度',
                data:Xdata,
                yAxis:0
            }]
    }
    $("#chart2").highcharts(option);
}
//获取图表3的数据
function getChart3(SelectSensorVal,time){
    let selectSense=SelectSensorVal;let times=time;
    if(selectSense == undefined){
        selectSense=$("#Chart3Select option:selected").val(); 
    }
    if(times == undefined){
        times=$("#chart3_time").val();
    }
    var startTimeSplit = times.split('-')[0].replace(" ", "").split('/'),
    endTimeSplit = times.split('-')[1].replace(" ", "").split('/');
    var startTime = startTimeSplit[2] + "-" + startTimeSplit[0] + "-" + startTimeSplit[1]+" 00:00:00";
    var endTime = endTimeSplit[2] + "-" + endTimeSplit[0] + "-" + endTimeSplit[1]+" 23:00:00";
    let url ="http://192.168.9.59:801/apis/result/queryAlllist/?"+"startTime="+startTime+"&endTime="+endTime+"&uniqure_code="+selectSense;
    // let url ="http://192.168.9.59:801/apis/result/queryAlllist/?"+"startTime="+startTime+"&endTime="+endTime+"&uniqure_code=03081400016";
    $.get(url, function (res) {
        if(res.msg=="success"){
            let dataList=[];
            res.data.forEach((li)=>{
                let column = li.column;
                let data = li.data;
                if(data){
                    for(let a=0;a<data.length;a++){
                        let li={}
                        for(let b=0;b<column.length;b++){
                            let key =column[b];
                            li[column[b]]=data[a][b];
                        }
                        dataList.push(li)
                }
                }
            
            })
            showChart3(dataList);
        }
    })
}
function showChart3(data){
    let Ydata=[]; let TimeData=[];
    data.forEach((item)=>{
        Ydata.push(item.JCSJ888A031*1);
        TimeData.push(item.time)
  })
  let option={
    chart: {
            type: 'line',
            style: {fontFamily: "'Unica One', sans-serif"},
            plotBorderColor: '#606063',
            zoomType: 'x',
            spacingRight: 20,
            height: 390
    },
    colors: [ '#7FBF7F', '#7F7FFF', '#FF6F10', '#8756D8', '#310F39', '#FF7F7F'],
    title: {text: ''},
    credits: {enabled: false},
    exporting: {enabled: false},
    subtitle: {text: ''},
    xAxis: {
        // type: 'datetime',
        categories: TimeData,
        tickInterval:30,
		labels: {
            enabled: true,
			formatter: function() {
				let arr = this.value.split(" ");
				if(arr[1]){
					return arr[1];
				}else{
					return this.value;
				}
				
            }
          }
    },
    yAxis: [{ // Secondary yAxis
        title: {
            text: '深度(m)',
            style: {
                color: '#4572A7'
            }
        },
        opposite: true
    }],
    tooltip: {
        formatter: function () {
           if(this.series.name == "深度"){
                let row;
                data.forEach((li)=>{
                    if(li.time == this.x){
                            row = li;
                    }
                })
                return "设备编码:[<b>" + row.JCSJ888A050 + "</b>]<br>时间:[" + row.time + "]<br>深度:[" + row.JCSJ888A031 + "(m)]";
            }
        }
    },
    plotOptions: {
            spline: {
                lineWidth: 1.5,
                states: {hover: {lineWidth: 2.5}},
                marker: {enabled: false}
            }
    },
    series: [
            {
                type: 'line',
                name: '深度',
                data:Ydata
            }
        ]
    }
    $("#chart3").highcharts(option);
}
//获取图表4的数据
function getChart4(SelectSensorVal,time){
    let selectSense=SelectSensorVal;let times=time;
    if(selectSense == undefined){
        selectSense=$("#Chart4Select option:selected").val(); 
    }
    if(times == undefined){
        times=$("#chart4_time").val();
    }
    var startTimeSplit = times.split('-')[0].replace(" ", "").split('/'),
    endTimeSplit = times.split('-')[1].replace(" ", "").split('/');
    var startTime = startTimeSplit[2] + "-" + startTimeSplit[0] + "-" + startTimeSplit[1]+" 00:00:00";
    var endTime = endTimeSplit[2] + "-" + endTimeSplit[0] + "-" + endTimeSplit[1]+" 23:00:00";
    let url ="http://192.168.9.59:801/apis/result/queryAlllist/?"+"startTime="+startTime+"&endTime="+endTime+"&uniqure_code="+selectSense;
    // let url ="http://192.168.9.59:801/apis/result/queryAlllist/?"+"startTime="+startTime+"&endTime="+endTime+"&uniqure_code=03081400016";
    $.get(url, function (res) {
        if(res.msg=="success"){
            let dataList=[];
            res.data.forEach((li)=>{
                let column = li.column;
                let data = li.data;
                if(data){
                    for(let a=0;a<data.length;a++){
                        let li={}
                        for(let b=0;b<column.length;b++){
                            let key =column[b];
                            li[column[b]]=data[a][b];
                        }
                        dataList.push(li)
                    }
                }
            })
            showChart4(dataList);
        }
    })
}
function showChart4(data){
    let Zdata=[]; let TimeData=[];
    data.forEach((item)=>{
        Zdata.push(item.JCSJ888A032*1);
        TimeData.push(item.time)
  })

  let option={
    chart: {
            type: 'line',
            style: {fontFamily: "'Unica One', sans-serif"},
            plotBorderColor: '#606063',
            zoomType: 'x',
            spacingRight: 20,
            height: 390
    },
    colors: [ '#7F7FFF', '#FF6F10', '#8756D8', '#310F39', '#FF7F7F'],
    title: {text: ''},
    credits: {enabled: false},
    exporting: {enabled: false},
    subtitle: {text: ''},
    xAxis: {
        // type: 'datetime',
        categories: TimeData,
        tickInterval:30,
		labels: {
            enabled: true,
			formatter: function() {
				let arr = this.value.split(" ");
				if(arr[1]){
					return arr[1];
				}else{
					return this.value;
				}
				
            }
          }
    },
    yAxis: [{ // Secondary yAxis
        title: {
            text: '电导率（mS/cm）',
            style: {
                color: '#00A4FF'
            }
        },
        opposite: true
    }],
    tooltip: {
        formatter: function () {
            if(this.series.name == "电导率"){
                let row;
                data.forEach((li)=>{
                    if(li.time == this.x){
                            row = li;
                    }
                })
                return "设备编码:[<b>" + row.JCSJ888A050 + "</b>]<br>时间:[" + row.time + "]<br>电导率:[" + row.JCSJ888A032 + "(mS/cm)]";
            }
        }
    },
    plotOptions: {
            spline: {
                lineWidth: 1.5,
                states: {hover: {lineWidth: 2.5}},
                marker: {enabled: false}
            }
    },
    series: [
            {
                type: 'line',
                name: '电导率',
                data:Zdata,
            }
        ]
    }
    $("#chart4").highcharts(option);
}
//table数据
function getTableData(SelectSensorVal,time){
     let selectSense=SelectSensorVal;let times=time;
     if(selectSense == undefined){
        selectSense=$("#tableSelect option:selected").val(); 
    }
    if(times ==undefined){
          times=$(".timeControl #lastTime").val();
    }
    var startTimeSplit = times.split('-')[0].replace(" ", "").split('/'),
    endTimeSplit = times.split('-')[1].replace(" ", "").split('/');
    var startTime = startTimeSplit[2] + "-" + startTimeSplit[0] + "-" + startTimeSplit[1]+" 00:00:00";
    var endTime = endTimeSplit[2] + "-" + endTimeSplit[0] + "-" + endTimeSplit[1]+" 23:59:59";
    // let url ="http://192.168.9.59:801/apis/result/queryAlllist/?"+"startTime="+startTime+"&endTime="+endTime+"&uniqure_code=03081400016";
    let url ="http://192.168.9.59:801/apis/result/queryAlllist?"+"startTime="+startTime+"&endTime="+endTime+"&uniqure_code="+selectSense;
    $.get(url, function (res) {
        if(res.msg=="success"){
            let dataList=[];
            res.data.forEach((li)=>{
                let column = li.column;
                let data = li.data;
                if(data){
                    for(let a=0;a<data.length;a++){
                        let li={}
                        for(let b=0;b<column.length;b++){
                            let key =column[b];
                            li[column[b]]=data[a][b];
                        }
                        dataList.push(li)
                    }
                }
            })
            layui.use(['table','layer','form','layedit','laydate'], function(){
                var table = layui.table;
                var layer=layui.layer;
                var layedit = layui.layedit;
                var form=layui.form;
                var $=layui.$;
                var laydate = layui.laydate;
                table.render({
                  elem: '#idTest'
                  ,data: dataList
                  ,contentType: "application/x-www-form-urlencoded"
                  ,page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                      layout: [ 'prev', 'page', 'next', 'skip','limit', 'count',] //自定义分页布局
                      //,curr: 5 //设定初始在第 5 页
                      ,limit:10 //一页显示多少条
                      ,limits:[5,10,15]//每页条数的选择项
                      ,groups: 2 //只显示 2 个连续页码
                      ,first: "首页" //不显示首页
                      ,last: "尾页" //不显示尾页
                      }
                      ,where:{ispage: true }
                      ,even:true
                      ,page: true  //是否启用分页
                      ,done:function(res, curr, count){ }
                      ,cols: [[
                                      ,{field:'time',  title: '时间',width:170}
                                      ,{field:'JCSJ888A030',  title: '摄氏度'}
                                      ,{field:'JCSJ888A031', title: '深度（m）'}
                                      ,{field:'JCSJ888A032', title: '电导率(mS/cm)'}
                                      ,{field:'JCSJ888A040', title: '设备入库时间'}
                                      ,{field:'JCSJ888A050', title: '设备唯一编码'}
                                      ,{field:'JCSJ888A060', title: '设备类型编号'}
                                      ,{field:'JCSJ888A070', title: '传感器'} 
      
                      ]]
                  });
          })
        }
    }) 
}




